package com.tian.service.impl;

import com.tian.entity.ChargeUserCoupon;
import com.tian.entity.UserCouponExpireTemporary;
import com.tian.enums.UserCouponStatusEnum;
import com.tian.mapper.ChargeUserCouponMapper;
import com.tian.mapper.UserCouponExpireTemporaryMapper;
import com.tian.service.UserCouponExpireService;
import com.tian.util.ChargeMarketRedisKeyPrefix;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * {@code @description:} 用户优惠券过期处理实现类
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-08-19 23:41
 * {@code @version:} 1.0
 */
@Slf4j
@Service
public class UserCouponExpireServiceImpl implements UserCouponExpireService {
    @Resource
    private UserCouponExpireTemporaryMapper userCouponExpireTemporaryMapper;
    @Resource
    private ChargeUserCouponMapper chargeUserCouponMapper;
    @Resource
    private RedissonClient redissonClient;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void expireUserCoupon() {
        Date expireDate = new Date();
        long count = userCouponExpireTemporaryMapper.countByExpireDate(expireDate);
        if (count == 0) {
            log.info("没有需要处理的用户优惠券");
            return;
        }
        for (long i = 0; i < count; i += 100) {
            List<UserCouponExpireTemporary> userCouponExpireTemporaries = userCouponExpireTemporaryMapper.selectByExpireDatePage(expireDate, i, 50);
            for (UserCouponExpireTemporary userCouponExpireTemporary : userCouponExpireTemporaries) {
                ChargeUserCoupon chargeUserCoupon = chargeUserCouponMapper.selectByPrimaryKey(userCouponExpireTemporary.getUserCouponId());
                if (chargeUserCoupon.getStatus() == UserCouponStatusEnum.INIT.getStatus()) {
                    chargeUserCoupon.setStatus(UserCouponStatusEnum.EXPIRED.getStatus());
                    //用户可用优惠券数量减1
                    redissonClient.getAtomicLong(ChargeMarketRedisKeyPrefix.USER_AVAILABLE_COUPON_COUNT_KEY + chargeUserCoupon.getUserId()).decrementAndGet();
                    chargeUserCouponMapper.updateByPrimaryKey(chargeUserCoupon);
                }
                userCouponExpireTemporaryMapper.doExpire(userCouponExpireTemporary.getId());
            }
        }
    }
}
